package account_manage

import (
	"fyne.io/fyne/v2"
	"fyne.io/fyne/v2/container"
	"fyne.io/fyne/v2/widget"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo/options"
	"go_gui/diy"
	"go_gui/g"
)

// ConvertView 账号数据转换
func ConvertView() fyne.CanvasObject {
	// binduid查询框
	_searchBindUidEntry := &widget.Entry{
		Wrapping:    fyne.TextWrapOff,
		PlaceHolder: "玩家uid或名字转账号",
		OnSubmitted: func(_ string) {
			searchBindUidFunc()
		},
	}
	AccountComp.SearchBindUidEntry = _searchBindUidEntry
	// binduid结果框
	_bindUidResEntry := &widget.Entry{
		Wrapping: fyne.TextWrapOff,
	}
	AccountComp.BindUidResEntry = _bindUidResEntry
	// binduid查询按钮
	_searchBindUidEntryButton := widget.NewButton(">>>>>>", searchBindUidFunc)
	view1 := container.NewGridWithColumns(
		4,
		_searchBindUidEntry,
		_searchBindUidEntryButton,
		_bindUidResEntry,
	)

	// uid查询框
	_searchUidEntry := &widget.Entry{
		Wrapping:    fyne.TextWrapOff,
		PlaceHolder: "账号转玩家uid",
		OnSubmitted: func(_ string) {
			searchUidFunc()
		},
	}
	AccountComp.SearchUidEntry = _searchUidEntry
	// uid结果框
	_uidResEntry := &widget.Entry{
		Wrapping: fyne.TextWrapOff,
	}
	AccountComp.UidResEntry = _uidResEntry
	// uid查询按钮
	_searchUidEntryButton := widget.NewButton(">>>>>>", searchUidFunc)
	view2 := container.NewGridWithColumns(
		4,
		_searchUidEntry,
		_searchUidEntryButton,
		_uidResEntry,
	)

	view := container.NewVBox(view1, view2)

	return view
}

func searchBindUidFunc() {
	_inputContent := AccountComp.SearchBindUidEntry.Text
	if _inputContent == "" {
		diy.ShowInformation("请输入玩家uid或名字", AccountComp.GameView)
		return
	}

	_options := new(options.FindOneOptions)
	_options.SetProjection(map[string]bool{
		"binduid": true,
	})
	_findOne := func(filter bson.M) map[string]any {
		return g.Mdb.FindOne("userinfo", filter, _options)
	}
	_res := _findOne(bson.M{"uid": _inputContent})
	if len(_res) == 0 {
		_res = _findOne(bson.M{"name": _inputContent})
	}
	if len(_res) == 0 {
		diy.ShowInformation("查无此人", AccountComp.GameView)
		AccountComp.BindUidResEntry.SetText("")
		return
	}

	AccountComp.BindUidResEntry.SetText(_res["binduid"].(string))
}

func searchUidFunc() {
	_inputContent := AccountComp.SearchUidEntry.Text
	if _inputContent == "" {
		diy.ShowInformation("请输入玩家uid", AccountComp.GameView)
		return
	}

	_options := new(options.FindOneOptions)
	_options.SetProjection(map[string]bool{
		"uid": true,
	})
	_findOne := func(filter bson.M) map[string]any {
		return g.Mdb.FindOne("userinfo", filter, _options)
	}
	_res := _findOne(bson.M{"binduid": _inputContent})
	if len(_res) == 0 {
		diy.ShowInformation("查无此人", AccountComp.GameView)
		AccountComp.UidResEntry.SetText("")
		return
	}

	AccountComp.UidResEntry.SetText(_res["uid"].(string))
}
